package dao;

import model.Message;
import utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tongchen
 * @create 2023-04-02 20:17
 */
public class MessageDao {
    //两个核心方法
    //方法1实现查询所有数据
    public List<Message> selectAll(){
        //创建四个变量
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        ArrayList<Message>list=new ArrayList<>();
        //建立连接
        try {
            connection= DBUtil.getConnection();
            //sql语句
            String sql="select *from message_wall";
            //获取执行对象
            statement=connection.prepareStatement(sql);
            //执行语句
             resultSet = statement.executeQuery();
             while(resultSet.next()){
                 //创建对象
                 Message message = new Message();
                 message.setSender(resultSet.getString(2));
                 message.setReceiver(resultSet.getString(3));
                 message.setContent(resultSet.getString(4));
                 //将对象加入集合
                 list.add(message);
             }
             return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.closeResources(connection, statement, resultSet);
        }
    }
    //方法二实现插入数据
    public int insert(Message message){
        Connection connection=null;
        PreparedStatement statement=null;
        try {
            connection=DBUtil.getConnection();
            //创建sql语句
            String sql="insert into message_wall values(null,?,?,?)";
            statement=connection.prepareStatement(sql);
            //设置参数
            statement.setString(1, message.getSender());
            statement.setString(2, message.getReceiver());
            statement.setString(3, message.getContent());
            //执行
            int res = statement.executeUpdate();
            //返回
            return res;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.closeResources(connection, statement, null);
        }
    }
}
